package com.xiaoxu.intranetweb.mybatisplusSzappdb.business.gypsumCompete;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.TSpecialPrice;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.service.impl.TSpecialPriceServiceImpl;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;

@Component
public class GypsumCompeteUtil {
    @Autowired
    private TSpecialPriceServiceImpl tSpecialPriceService;
    public String randomDays(String dateString, String pdtId,  String priceTypeId, String dataFrom) {
        // 解析日期字符串为YearMonth对象，因为字符串只包含年月
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
        YearMonth yearMonth = YearMonth.parse(dateString, formatter);

        // 获取指定月份的最大天数
        int daysInMonth = yearMonth.lengthOfMonth();

        // 构建当月天数的列表
        List<Integer> days = new ArrayList<>();
        for (int i = 1; i <= daysInMonth; i++) {
            days.add(i);
        }

        // 查询已被占用的天数，直接根据年月进行匹配
        QueryWrapper<TSpecialPrice> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("START_TIME")
                .eq("PRICE_TYPE_ID", priceTypeId)
                .eq("PDT_ID", pdtId)
                .eq("DATA_FROM", dataFrom)
                .ge("START_TIME", yearMonth.atDay(1).atStartOfDay().toString()) // 大于等于当月第一天
                .lt("START_TIME", yearMonth.plusMonths(1).atDay(1).atStartOfDay().toString()); // 小于下个月第一天

        List<TSpecialPrice> occupiedDaysList = tSpecialPriceService.list(queryWrapper);

        // 使用Set来存储占用的天数，确保唯一性
        Set<Integer> occupiedDays = new HashSet<>();
        for (TSpecialPrice occupiedDay : occupiedDaysList) {
            LocalDate occupiedLocalDate = occupiedDay.getStartTime().toLocalDate();
            occupiedDays.add(occupiedLocalDate.getDayOfMonth());
        }

        // 移除占用天数
        days.removeAll(occupiedDays);

        // 如果没有剩余天数则返回null
        if (days.isEmpty()) {
            return null;
        }

        // 随机选择剩余天数
        // 使用ThreadLocalRandom
        int randomIndex = ThreadLocalRandom.current().nextInt(days.size());
        int selectedDay = days.get(randomIndex);

        // 返回格式化的随机日期字符串，设定时间为当天的0点
        String monthStr = (yearMonth.getMonthValue() < 10) ? "0" + yearMonth.getMonthValue() : String.valueOf(yearMonth.getMonthValue());
        String dayStr = (selectedDay < 10) ? "0" + selectedDay : String.valueOf(selectedDay);
        return yearMonth.getYear() + "-" + monthStr + "-" + dayStr + " 00:00:00";
    }


}
